//
//  HomeXiaoXiViewController.m
//  买家版首页
//
//  Created by 王天义 on 16/8/15.
//  Copyright © 2016年 TYWang. All rights reserved.
//

#import "HomeXiaoXiViewController.h"
#import "HomeXiaoXiCell.h"
#import "HomeXiaoXiModel.h"

@interface HomeXiaoXiViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *_Id;
}
@property (nonatomic ,strong)UITableView *xiaoxiTableView;
@end

@implementation HomeXiaoXiViewController

#pragma mark --- 懒加载

- (NSMutableArray *)datas{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    默认【下拉刷新】
    self.xiaoxiTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getMessageRef)];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.title = @"消息";
    
    [self creatXiaoXiTableView];
    [self setExtraCellLineHidden:self.xiaoxiTableView];
    [self getMessageRef];
}

- (void)getMessageRef{
    [self.xiaoxiTableView.mj_header beginRefreshing];
    [self getMessageRequest];
   
}

- (void)creatXiaoXiTableView{

    if (self.xiaoxiTableView == nil) {
        self.xiaoxiTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, XNWindowHeight - 49) style:UITableViewStylePlain];
    }
    self.xiaoxiTableView.dataSource = self;
    self.xiaoxiTableView.delegate = self;
    self.view = self.xiaoxiTableView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"HomeXiaoXiCellID";
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([HomeXiaoXiCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
        nibsRegistered = YES;
    }
    HomeXiaoXiCell *cell = (HomeXiaoXiCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.yuanquanView.badgeCenterOffset = CGPointMake(0, 0);

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    HomeXiaoXiModel *model = self.datas[indexPath.row];
    if (model.IsRead) {
        [cell.yuanquanView clearBadge];
    }else{
        [cell.yuanquanView showBadge];
    }
    if (model.ShopId) {
        cell.nameLabel.text = model.ShopName;
    }else{
        cell.nameLabel.text = @"服务器消息";
    }
    cell.infoLabel.text = model.MessageContent;
    cell.dateLabel.text = model.SendTime;
    [cell.iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://121.42.204.177:9999%@",model.Logo]] placeholderImage:nil];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeXiaoXiModel *model = self.datas[indexPath.row];
    _Id = model.Id;
    
    HomeXiaoXiCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell.yuanquanView clearBadge];
    [self updateIsReadByIds];
}

//设置超出数据源的tableview的分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return XNWindowHeight / 6;
    HomeXiaoXiModel *xiaoXiHomepageModel = self.datas[indexPath.row];
    NSString * titleString = xiaoXiHomepageModel.MessageContent;
    CGSize sizeToFit_Title;
    sizeToFit_Title = [titleString boundingRectWithSize:CGSizeMake(0, 100) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:15]} context:nil].size;
    return sizeToFit_Title.height+50;
}

#pragma mark --- 获取消息列表
- (void)getMessageRequest{
    NSDictionary *par = @{@"ShouJiHao":GETPHONE,
                          @"Token":GETTOKEN,
                          @"Duuid":GETUUID};
    [CQNetWorkTools GETWithURL:GetMessageLogBySendTo par:par success:^(id responseObject) {
        if ([[responseObject objectForKey:@"Err"] intValue]) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        }else{
            
            NSArray *dataArr = [responseObject objectForKey:@"MessageLogs"];
            [self.datas removeAllObjects];
            for (NSDictionary *dict in dataArr) {
                HomeXiaoXiModel *model = [HomeXiaoXiModel mj_objectWithKeyValues:dict];
                [self.datas addObject:model];
            }
            // 刷新表格
            [self.xiaoxiTableView reloadData];
            
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.xiaoxiTableView.mj_header endRefreshing];

        }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        [SVProgressHUD  showWithStatus:@"请检查网络"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        [self.xiaoxiTableView.mj_header endRefreshing];
    }];
}
- (void)updateIsReadByIds{
    NSDictionary *par = @{@"ShouJiHao":GETPHONE,
                          @"Token":GETTOKEN,
                          @"Duuid":GETUUID,
                          @"Ids":_Id};
    
    [CQNetWorkTools GETWithURL:UpdateIsReadByIds par:par success:^(id responseObject) {
        if ([[responseObject objectForKey:@"Err"] intValue]) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        }else{
//            // 刷新表格
//            [self.xiaoxiTableView reloadData];
            
//            // 拿到当前的下拉刷新控件，结束刷新状态
//            [self.xiaoxiTableView.mj_header endRefreshing];
        }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        [SVProgressHUD  showWithStatus:@"请检查网络"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
    }];
}

- (void)dismiss{
    [SVProgressHUD dismiss];
}
@end
